<template>
  <div class="carousel">
    <div
      class="carousel-inner"
      :style="{ transform: `translateX(-${currentSlide * 100}%)` }"
    >
      <div v-for="(image, index) in images" :key="index" class="carousel-item">
        <img :src="image" alt="Slide" />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from "vue";

export default {
  name: "Carousel",
  props: {
    images: {
      type: Array,
      required: true,
    },
  },
  setup(props) {
    const currentSlide = ref(0);
    let interval; // 定义 interval 变量

    const nextSlide = () => {
      currentSlide.value = (currentSlide.value + 1) % props.images.length;
    };

    // 设置定时器
    const startAutoPlay = () => {
      interval = setInterval(nextSlide, 3000); // 每 3 秒切换一次
    };

    // 清除定时器
    const stopAutoPlay = () => {
      clearInterval(interval);
    };

    onMounted(() => {
      startAutoPlay();
    });

    onBeforeUnmount(() => {
      stopAutoPlay();
    });

    return {
      currentSlide,
      nextSlide,
      prevSlide: () => {
        currentSlide.value =
          (currentSlide.value - 1 + props.images.length) % props.images.length;
      },
    };
  },
};
</script>

<style scoped>
.carousel {
  position: relative;
  width: 100%;
  overflow: hidden;
}

.carousel-inner {
  display: flex;
  transition: transform 0.5s ease-in-out;
}

.carousel-item {
  min-width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.carousel-item img {
  width: 100%;
  height: 200px;
  border-radius:10px;
}

.carousel-control-prev,
.carousel-control-next {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  padding: 10px;
  cursor: pointer;
}

.carousel-control-prev {
  left: 10px;
}

.carousel-control-next {
  right: 10px;
}
</style>
